package com.soriya.nestlive.screen.live

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.OutlinedButton
import androidx.compose.material.RadioButton
import androidx.compose.material.Slider
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.VideogameAsset
import androidx.compose.material.icons.twotone.Message
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat
import androidx.core.net.toFile
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Observer
import com.soriya.nestlive.R
import com.soriya.nestlive.application.MyApplication
import com.soriya.nestlive.component.CustomEditText
import com.soriya.nestlive.component.LiveChatArea
import com.soriya.nestlive.component.LiveOptionButton
import com.soriya.nestlive.component.LiveTitle
import com.soriya.nestlive.component.MediumText
import com.soriya.nestlive.component.MediumTitle
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.component.ScreenConstraintContent
import com.soriya.nestlive.component.SmallAdditionalText
import com.soriya.nestlive.component.SmallText
import com.soriya.nestlive.component.SmallTitle
import com.soriya.nestlive.constant.CommonConstant
import com.soriya.nestlive.constant.StreamConstant
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.extend.toFormatString
import com.soriya.nestlive.model.Category
import com.soriya.nestlive.model.Channel
import com.soriya.nestlive.model.Live
import com.soriya.nestlive.service.ScreenLiveService
import com.soriya.nestlive.util.ToastUtil
import com.soriya.nestlive.viewmodel.CategoryModel
import com.soriya.nestlive.viewmodel.ChannelModel
import com.soriya.nestlive.viewmodel.LiveModel
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.io.File
import java.util.Date
import java.util.UUID

lateinit var intent: Intent

@RequiresApi(Build.VERSION_CODES.Q)
@Composable
fun GameStreamInfoScreen(
    toLive: () -> Unit
) {
    val context = LocalContext.current

    intent = Intent(context, ScreenLiveService::class.java)

    // 帧率
    var frameRate by remember {
        mutableStateOf(StreamConstant.DEFAULT_FRAME_RATE)
    }
    // 屏幕方向
    var orientation by remember {
        mutableStateOf(StreamConstant.SCREEN_HORIZONTAL)
    }
    // 码率
    var bitRate by remember {
        mutableStateOf(StreamConstant.DEFAULT_BIT_RATE)
    }

    val mediaProjectionManager =
        context.getSystemService(ComponentActivity.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager

    val resultContracts = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult(),
        onResult = {
            if (it.resultCode == Activity.RESULT_OK && it.data != null) {
//                intent.putExtra("channelId", 100L)
                intent.putExtra("resultCode", it.resultCode)
                intent.putExtra("data", it.data)
                intent.putExtra("frameRate", frameRate)
                intent.putExtra("orientation", orientation)
                intent.putExtra("bitRate", bitRate)
                // 录屏必须使用前台Service
                context.startService(intent)
                toLive()
            }
        }
    )

    val permissionReq = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = {
            if (it) {
                Toast.makeText(context, "授权成功", Toast.LENGTH_SHORT).show()
                resultContracts.launch(
                    mediaProjectionManager.createScreenCaptureIntent()
                )
            } else {
                Toast.makeText(context, "授权失败", Toast.LENGTH_SHORT).show()
            }
        }
    )

    StreamInfoUI(
        frameRate = frameRate,
        bitRate = bitRate,
        onFrameRateChange = { frameRate = it },
        orientation = orientation,
        onOrientationChange = { orientation = it },
        onBitRateChange = { bitRate = it }
    ) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            permissionReq.launch(Manifest.permission.RECORD_AUDIO)
        } else {
            resultContracts.launch(
                mediaProjectionManager.createScreenCaptureIntent()
            )
        }
    }
}

@Composable
fun GameStreamLiveScreen(
    back: () -> Unit
) {
    val context = LocalContext.current

    val liveModel: LiveModel = hiltViewModel()
    val channelModel: ChannelModel = hiltViewModel()
//    val channel by channelModel.getMyChannel().collectAsState(initial = null)
    val channel by channelModel.channelDetail.collectAsState()
    channelModel.getMyChannel()

    val coroutineScope = rememberCoroutineScope()


    DisposableEffect(Unit) {

//        liveModel.createLive()
        onDispose {
            context.stopService(intent)
            coroutineScope.launch {
                liveModel.stopLive().collect {}
            }
        }
    }

    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        Image(
            painter = painterResource(id = R.mipmap.live_bg),
            contentScale = ContentScale.Crop,
            contentDescription = "Live Background",
            modifier = Modifier
                .fillMaxSize()
                .blur(20.dp)
        )

        ScreenColumnContent {
            LiveTitle(
                onExit = {
                    coroutineScope.launch {
                        liveModel.stopLive().collectLatest {
                            context.stopService(intent)
                        }
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 20.dp)
            )

            Column(
                verticalArrangement = Arrangement.Bottom,
                modifier = Modifier
                    .weight(1F)
            ) {
                if (channel != null && channel != Channel.EMPTY) LiveChatArea(
                    channelId = channel!!.id ?: 0L,
                    modifier = Modifier
                        .padding(bottom = 10.dp)
                )
            }

            Row(
                modifier = Modifier
                    .padding(bottom = UIValue.VERTICAL_PADDING)
                    .fillMaxWidth()
                    .height(60.dp)
            ) {
                LiveOptionButton(icon = Icons.TwoTone.Message, contentDescription = "Chat") {}
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterialApi::class,
    ExperimentalComposeUiApi::class
)
@Composable
private fun StreamInfoUI(
    frameRate: Int = StreamConstant.DEFAULT_FRAME_RATE,
    orientation: Int = StreamConstant.SCREEN_HORIZONTAL,
    bitRate: Double = StreamConstant.DEFAULT_BIT_RATE,
    onOrientationChange: (Int) -> Unit = {},
    onGameVolumeChange: (Float) -> Unit = {},
    onMicVolumeChange: (Float) -> Unit = {},
    onFrameRateChange: (Int) -> Unit = {},
    onBitRateChange: (Double) -> Unit = {},
    startLive: () -> Unit
)  {
    val context = LocalContext.current as Activity

    val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)

    val coroutineScope = rememberCoroutineScope()

    val channelModel: ChannelModel = hiltViewModel()

    val liveModel: LiveModel = hiltViewModel()

    val streamingConfig = context.getSharedPreferences(CommonConstant.STREAMING_CONFIG_KEY, Context.MODE_PRIVATE)

    var title by remember {
        mutableStateOf(streamingConfig.getString("title", "") ?: "")
    }

    var coverFile: File? = null

    val cover by remember {
         mutableStateOf(streamingConfig.getString("cover", "") ?: "")
    }

    var category by remember {
        mutableStateOf<Category?>(null)
    }

    val tags = remember {
        streamingConfig.getString("tags", null)?.split("|")?.toMutableStateList() ?: mutableStateListOf()
    }

    var desc by remember {
        mutableStateOf(streamingConfig.getString("desc", "") ?: "")
    }

    var modalType by remember {
        mutableStateOf(-1)
    }

    val observer = Observer<Uri?> {
        Log.i("SoRiya", "ImageUri: $it")
        coverFile = it?.toFile()
    }

    val imagePickerLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri ->
        if (uri == null) return@rememberLauncherForActivityResult

        MyApplication.instance.imageResult.observeForever(observer)
        val options = UCrop.Options()
        options.apply {

            // 修改标题栏颜色
//            options.setToolbarColor(getResources().getColor(R.color.teal_200));
            // 修改状态栏颜色
//            options.setStatusBarColor(getResources().getColor(R.color.teal_700));

            // 是否隐藏底部工具
            setHideBottomControls(false)

            // 图片格式
            setCompressionFormat(Bitmap.CompressFormat.JPEG)

            // 设置图片压缩质量
            setCompressionQuality(100)

            // 是否让用户调整范围(默认false)，如果开启，可能会造成剪切的图片的长宽比不是设定的
            // 如果不开启，用户不能拖动选框，只能缩放图片
            setFreeStyleCropEnabled(true)

            // 圆
            setCircleDimmedLayer(false)

            // 不显示网格线
            setShowCropGrid(false)

            UCrop.of(uri, Uri.fromFile(File(context.getExternalFilesDir("crop_cache")!!.path, UUID.randomUUID().toString().replace("-", "") + ".jpg")))
                .withAspectRatio(16F, 9F)
                .withMaxResultSize(1280, 720) // 720P
                .withOptions(options)
                .start(context)
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            MyApplication.instance.imageResult.value = null
            MyApplication.instance.imageResult.removeObserver(observer)
        }
    }

    val keyboardController = LocalSoftwareKeyboardController.current
    LaunchedEffect(sheetState.isVisible) {
        if (!sheetState.isVisible) {
            keyboardController?.hide()
        }
    }

    ModalBottomSheetLayout(
        sheetContent = {
            // 底部动作条
            when (modalType) {
                0 -> {
                    CategoryModal(
                        onSelected = {
                            category = it
                            coroutineScope.launch {
                                sheetState.hide()
                            }
                        }
                    )
                }
                1 -> {
                    TagModal(
                        onComplete = {
                            tags += it
                            coroutineScope.launch {
                                sheetState.hide()
                            }
                        }
                    )
                }
            }
        },
        sheetState = sheetState,
        sheetBackgroundColor = MaterialTheme.colors.background
    ) {
        ScreenColumnContent {
            Column(
                modifier = Modifier
                    .weight(1F)
                    .verticalScroll(rememberScrollState())
            ) {
                Title(text = "直播封面")
                Button(onClick = {
                    imagePickerLauncher.launch("image/*")
                }) {
                    SmallText(text = "选择封面")
                }

                Title(text = "直播标题")
                CustomEditText(
                    value = title,
                    onValueChange = { title = it },
                    shape = RoundedCornerShape(UIValue.SMALLER_RADIUS)
                )

                Title(text = "分类") {
                    Row(
                        modifier = Modifier.clickable {
                            coroutineScope.launch {
                                modalType = 0
                                sheetState.show()
                            }
                        }
                    ) {
                        CompositionLocalProvider(LocalContentColor provides MaterialTheme.colors.primary) {
                            SmallTitle(text = "选择分类")
                            Icon(imageVector = Icons.Default.Add, contentDescription = "Select Category")
                        }
                    }
                }

                if (category != null) FlowRow(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    TagItem(modifier = Modifier.padding(end = 6.dp), tag = category!!.categoryName, key = 0)
                } else Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(36.dp)
                ) {
                    SmallAdditionalText(text = "无分类")
                }

                Title(text = "标签") {
                    Row(
                        modifier = Modifier.clickable {
                            coroutineScope.launch {
                                modalType = 1
                                sheetState.show()
                            }
                        }
                    ) {
                        CompositionLocalProvider(LocalContentColor provides MaterialTheme.colors.primary) {
                            SmallTitle(text = "添加标签")
                            Icon(imageVector = Icons.Default.Add, contentDescription = "Add Tags")
                        }
                    }
                }

                if (tags.isNotEmpty()) FlowRow(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    tags.forEachIndexed { index, item ->
                        TagItem(modifier = Modifier.padding(end = 6.dp), tag = item, key = index) {
                            if (it != null) {
                                tags.removeAt(it)
                            }
                        }
                    }
                } else Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(36.dp)
                ) {
                    SmallAdditionalText(text = "无标签")
                }

                Title(text = "描述")
                CustomEditText(
                    value = desc,
                    onValueChange = { desc = it },
                    shape = RoundedCornerShape(UIValue.SMALLER_RADIUS)
                )

                Title(text = "游戏类型")
                Row {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = orientation == StreamConstant.SCREEN_HORIZONTAL, onClick = {
                            onOrientationChange(StreamConstant.SCREEN_HORIZONTAL)
                        })
                        MediumText(text = "横屏游戏")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = orientation == StreamConstant.SCREEN_VERTICAL, onClick = {
                            onOrientationChange(StreamConstant.SCREEN_VERTICAL)
                        })
                        MediumText(text = "竖屏游戏")
                    }
                }

                Title(text = "音量")
                var gameVolume by remember {
                    mutableStateOf(0.5F)
                }
                var micVolume by remember {
                    mutableStateOf(0.6F)
                }
                Column {
                    CompositionLocalProvider (LocalContentColor provides MaterialTheme.colors.primary) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.VideogameAsset,
                                contentDescription = "Game Volume"
                            )
                            Spacer(modifier = Modifier.width(UIValue.HORIZONTAL_PADDING))
                            Slider(value = gameVolume, onValueChange = {
                                gameVolume = it
                                onGameVolumeChange(it)
                            })
                        }

                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.Mic,
                                contentDescription = "Microphone Volume"
                            )
                            Spacer(modifier = Modifier.width(UIValue.HORIZONTAL_PADDING))
                            Slider(value = micVolume, onValueChange = {
                                micVolume = it
                                onMicVolumeChange(it)
                            })
                        }
                    }
                }

                Title(text = "帧率")
                Row {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = frameRate == 15, onClick = {
                            onFrameRateChange(15)
                        })
                        MediumText(text = "15")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = frameRate == 30, onClick = {
                            onFrameRateChange(30)
                        })
                        MediumText(text = "30")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = frameRate == 60, onClick = {
                            onFrameRateChange(60)
                        })
                        MediumText(text = "60")
                    }
                }

                Title(text = "分辨率")
                Row {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = bitRate == 0.03, onClick = {
                            onBitRateChange(0.03)
                        })
                        MediumText(text = "标清")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = bitRate == 0.1, onClick = {
                            onBitRateChange(0.1)
                        })
                        MediumText(text = "高清")
                    }

                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(selected = bitRate == 0.4, onClick = {
                            onBitRateChange(0.4)
                        })
                        MediumText(text = "超清")
                    }
                }
            }
            Box(
                modifier = Modifier
                    .padding(vertical = UIValue.VERTICAL_PADDING.times(2))
            ) {
                Button(
                    onClick = {
                        if (cover.isEmpty() && coverFile == null) {
                            ToastUtil.show(context, "请选择封面")
                            return@Button
                        }
                        if (category == null) {
                            ToastUtil.show(context, "请选择分类")
                            return@Button
                        }

                        coroutineScope.launch {
                            channelModel.channelDetail.collectLatest { channel ->
                                if (channel == null || channel == Channel.EMPTY) return@collectLatest

                                val live = Live(
                                    channelId = channel.id!!,
                                    categoryId = category!!.id,
                                    liveName = title,
                                    liveDesc = desc,
                                    cover = cover,
                                    tags = tags.filter { it.isNotEmpty() }.joinToString("|"),
                                    orientation = if (orientation == StreamConstant.SCREEN_HORIZONTAL) 0 else 1,
                                    viewers = 0,
                                    startTime = Date().toFormatString(),
                                    duration = 0F
                                )

                                liveModel.createLive(live, coverFile).collectLatest { _live ->
                                    _live?.let {
                                        val edit = streamingConfig.edit()
                                        edit.putString("title", it.liveName)
                                        edit.putString("cover", it.cover)
                                        edit.putString("desc", it.liveDesc)
                                        edit.putString("tags", it.tags)
                                        edit.apply()
                                    }
                                    startLive()
                                }
                            }
                        }

                        channelModel.getMyChannel()
                    },
                    shape = RoundedCornerShape(50),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp)
                ) {
                    MediumText(text = "开始直播")
                }
            }
        }
    }
}